package com.sctvcloud.longchang.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.longchang.R;
import com.sctvcloud.longchang.base.BaseActivity;
import com.sctvcloud.longchang.beans.Branch;
import com.sctvcloud.longchang.beans.BranchBean;
import com.sctvcloud.longchang.beans.DepartmentAndTownBean;
import com.sctvcloud.longchang.beans.DepartmentAndTownItem;
import com.sctvcloud.longchang.http.AbsListNetCallback;
import com.sctvcloud.longchang.http.AbsNetCallBack;
import com.sctvcloud.longchang.http.NetUtils;
import com.sctvcloud.longchang.http.ParamsEditor;
import com.sctvcloud.longchang.ui.adapter.DepartAdapter;
import com.sctvcloud.longchang.ui.adapter.DepartmentAndTownAdapter;
import com.sctvcloud.longchang.ui.utils.GSFPlayerScreenControllImp;
import com.sctvcloud.longchang.ui.utils.TitleUtils;
import com.sctvcloud.longchang.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 选择部门、乡镇
 */
public class UserSelectAscriptionActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener {

    @BindView(R.id.rebllion_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView rebllion_list;
    @BindView(R.id.search_key_ct)
    protected CustomFontEditText searchCt;

    @BindView(R.id.title_top_title)
    protected CustomFontTextView title_top_title;
    @BindView(R.id.title_top_back)
    protected ImageView backImg;
    @BindView(R.id.title_top_edit_topic)
    protected CustomFontTextView confirm;
    private DepartmentAndTownAdapter mAdapter;
    private boolean mIsLoading = false;
    public static final String EX_TYPE = "ex_type";
    private String type;//1 部门， 2 乡镇

    private List<DepartmentAndTownItem> list = new ArrayList<DepartmentAndTownItem>();
    private DepartmentAndTownBean branch;
    private int id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        type = getIntent().getStringExtra(EX_TYPE);
        if (null != UserManager.getInstance().getUser() && null != UserManager.getInstance().getUser().getDepartmentAndTown()) {
            id = UserManager.getInstance().getUser().getDepartmentAndTown().getId();
        }
        initView();

    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_user_select_ascription);
        ButterKnife.bind(this);
    }

    private void initView() {

        title_top_title.setVisibility(View.VISIBLE);
        title_top_title.setText("部门街镇");
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != branch) {
                    Intent intent = new Intent();
                    intent.putExtra("departmentAndTownId", branch.getId());
                    intent.putExtra("departmentAndTown", branch.getDepTownName());
                    intent.putExtra("type", type);
                    setResult(RESULT_OK, intent);
                }
                finish();
            }
        });


        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        rebllion_list.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rebllion_list.setItemAnimator(new DefaultItemAnimator());
        refreshLayout.autoRefresh();
        backImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    private void initPos(int id) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getId() == id) {
                branch = list.get(i);
                list.get(i).setChoose(true);
                mAdapter.notifyDataSetChanged();
                return;
            }
        }

//        if (list.size() > 0) {
//            list.get(0).setChoose(true);
//            branch = list.get(0);
//            mAdapter.notifyDataSetChanged();
//        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            String key = searchCt.getText().toString().trim();
            if (TextUtils.isEmpty(key)) {
                toast("搜索关键词不能为空");
                return false;
            }
            getData(key);
        }
        return super.dispatchKeyEvent(event);
    }

    private void getData(String keyWord) {
        list.clear();
        ParamsEditor pe = new ParamsEditor();
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        pe.put("type", type);
        pe.put("departmentAndTown", keyWord);
        NetUtils.getNetAdapter().getDepartmentAndTownList(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsListNetCallback<DepartmentAndTownItem>(null) {
            @Override
            public void onSuc(List<DepartmentAndTownItem> data) {
                if (ListUtils.isListValued(data)) {
                    list.addAll(data);
                    initData();
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(R.string.loading_no_data);
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });

    }


    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        mIsLoading = true;

        String key = searchCt.getText().toString().trim();
        getData(key);
    }

    private void initData() {
        if (mAdapter == null) {
            mAdapter = new DepartmentAndTownAdapter(this, list).setItemInternalClick(itemClick);
            rebllion_list.setAdapter(mAdapter);
        } else {
            mAdapter.setData(list);
        }

        initPos(id);
    }


    private synchronized void onNetFinish() {
        mIsLoading = false;
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
    }


    OnItemInternalClick itemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            switch (view.getId()) {
                case R.id.re_top:
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setChoose(false);
                    }
                    list.get(position).setChoose(true);
                    branch = list.get(position);
                    mAdapter.notifyDataSetChanged();
                    break;

            }
        }
    };


    @OnClick({R.id.search_clean})
    protected void OnClean(View v) {
        switch (v.getId()) {
            case R.id.search_clean:
                searchCt.setText("");
                getData("");
                break;
        }
    }

}

